package com.sanron.sunweather.fragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sanron.sunweather.R;
import com.sanron.sunweather.common.IconManager;
import com.sanron.sunweather.entity.InstantWeather;
import com.sanron.sunweather.entity.Weather;
import com.sanron.sunweather.entity.WeatherData;
import com.sanron.sunweather.event.AboveEvent;
import com.sanron.sunweather.utils.DateUtils;
import com.sanron.sunweather.view.PetalContanier;
import com.sanron.sunweather.view.PetalView;
import com.sanron.sunweather.view.RotateView;
import com.sanron.sunweather.view.ScrollText;

public class AboveFrag extends BaseFragment implements OnClickListener {

	private View contentView;

	/**
	 * 顶栏view
	 */
	private ViewGroup topView;
	private TextView tvCity;
	private TextView tvUpdateTime;
	private ImageView ivShare;
	private ImageView ivMenu;

	/**
	 * 中间显示的即时天气
	 */
	private ViewGroup centerView;
	private ImageView ivWeatherIcon;
	private ImageView ivSun;
	private TextView tvTemperature;
	private TextView tvTempLowHigh;
	private TextView tvHumidity;
	private TextView tvType;
	private TextView tvNightType;
	private TextView tvLunarDate;
	private TextView tvDate;
	private TextView tvWind;

	/**
	 * 底部
	 */
	private ViewGroup bottomView;
	private RotateView rotateView;
	private PetalContanier petals;
	private ScrollText scrollText;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.fragment_above, null);
		initView();
		setListener();
		return contentView;
	}

	private void initView() {

		topView = (ViewGroup) contentView.findViewById(R.id.top);
		tvCity = (TextView) topView.findViewById(R.id.tv_city);
		tvUpdateTime = (TextView) topView.findViewById(R.id.tv_update_time);
		ivShare = (ImageView) topView.findViewById(R.id.iv_share);
		ivMenu = (ImageView) topView.findViewById(R.id.iv_menu);

		centerView = (ViewGroup) contentView.findViewById(R.id.center);
		ivWeatherIcon = (ImageView) centerView
				.findViewById(R.id.iv_weather_icon);
		tvTemperature = (TextView) centerView.findViewById(R.id.tv_temperature);
		tvTempLowHigh = (TextView) centerView
				.findViewById(R.id.tv_temperature_low_high);
		tvHumidity = (TextView) centerView.findViewById(R.id.tv_humidity);
		tvType = (TextView) centerView.findViewById(R.id.tv_weather_type);
		tvNightType = (TextView) centerView
				.findViewById(R.id.tv_weather_type_night);
		tvLunarDate = (TextView) centerView.findViewById(R.id.tv_lunar_date);
		tvDate = (TextView) centerView.findViewById(R.id.tv_date);
		tvWind = (TextView) centerView.findViewById(R.id.tv_wind);
		// 设置时间
		SimpleDateFormat sdf = new SimpleDateFormat("MM月dd号 E", Locale.CHINA);
		tvDate.setText(sdf.format(new Date()));

		bottomView = (ViewGroup) contentView.findViewById(R.id.bottom);
		rotateView = (RotateView) bottomView.findViewById(R.id.rotate_view);
		petals = (PetalContanier) bottomView.findViewById(R.id.petals);
		scrollText = (ScrollText) bottomView.findViewById(R.id.tv_state_tip);
	}

	private void setListener() {

		topView.setOnClickListener(this);
		centerView.setOnClickListener(this);
		ivMenu.setOnClickListener(this);

		rotateView.setOnScrollListener(new RotateView.OnScrollListener() {
			@Override
			public void onScroll(int offY) {
				petals.setTranslationY(petals.getTranslationY() - offY);
				scrollText.setTranslationY(petals.getTranslationY() - offY);
			}
		});

		rotateView
				.setOnStateChangeListener(new RotateView.OnStateChangeListener() {

					@Override
					public void onStateChange(int state, int oldState) {
						eventBus.post(new AboveEvent(
								AboveEvent.TYPE_BOTTOM_STATE_CHANGE, state));
					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.iv_menu: {
			eventBus.post(new AboveEvent(AboveEvent.TYPE_TOP_MENU_CLICK, null));
		}
			break;

		case R.id.center: {
			eventBus.post(new AboveEvent(AboveEvent.TYPE_CENTER_CLICK, null));
		}
			break;

		}
	}

	/**
	 * 设置定位状态text
	 */
	public void setLocationState(final String text) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				scrollText.addText(text);
			}
		});
	}

	/**
	 * 设置view
	 */
	@Override
	protected void updateViews() {
		List<Weather> weathers = weatherData.getWeathers();

		// 设置顶部的城市和更新时间
		tvCity.setText(weatherData.getCity());
		long time = (System.currentTimeMillis() - weatherData.getUpdateTime()
				.getTime().getTime()) / 1000 / 60;
		if (time < 60) {
			tvUpdateTime.setText(time + "分钟前");
		} else {
			tvUpdateTime.setText(time / 60 + "小时前");
		}

		SimpleDateFormat sdf = new SimpleDateFormat("E", Locale.CHINA);
		Calendar calendar = Calendar.getInstance();
		for (int i = 1; i < weathers.size(); i++) {
			Weather weather = weathers.get(i);
			Calendar weatherTime = weather.getTime();
			PetalView petalView = (PetalView) petals.getChildAt(i - 1);
			int iconId = IconManager.getTypeSmallIcon(weather.getDayType(),true);
			petalView.getWeatherView().setImageResource(iconId);
			petalView.getTemperatureView().setText(
					weather.getHighTEMP() + "°~" + weather.getLowTEMP() + "°");
			if (calendar.get(Calendar.MONTH) == weatherTime.get(Calendar.MONTH)
					&& calendar.get(Calendar.YEAR) == weatherTime
							.get(Calendar.YEAR)) {
				// 判断哪个是今天和明天天气
				if (calendar.get(Calendar.DAY_OF_YEAR) == weatherTime
						.get(Calendar.DAY_OF_YEAR)) {
					petalView.getWeekDayView().setText("今天");
					continue;
				} else if (calendar.get(Calendar.DAY_OF_YEAR) + 1 == weatherTime
						.get(Calendar.DAY_OF_YEAR)) {
					petalView.getWeekDayView().setText("明天");
					continue;
				}
			}
			petalView.getWeekDayView().setText(
					sdf.format(weather.getTime().getTime()));
		}

		InstantWeather instantWeather = weatherData.getInstantWeather();
		tvTemperature.setText(instantWeather.getInstantTEMP() + "°");
		tvWind.setText(instantWeather.getWindDirection() + " "
				+ instantWeather.getWindPower());
		tvHumidity.setText(instantWeather.getHumidity());

		//判断白天黑夜
		int dayOrNight = DateUtils.dayOrNight(weatherData.getInstantWeather()
				.getSunriseTime(), weatherData.getInstantWeather()
				.getSunsetTime());
		if (dayOrNight == 0) {
			Weather yestaday = weatherData.getWeathers().get(0);
			tvTempLowHigh.setText("最低 " + yestaday.getLowTEMP() + "°");
			tvType.setText(yestaday.getNightType());
		} else if (dayOrNight == 1) {
			Weather today = weatherData.getWeathers().get(1);
			tvTempLowHigh.setText(today.getHighTEMP() + "°~"
					+ today.getLowTEMP() + "°");
			tvType.setText(today.getDayType());
			tvNightType.setText("夜里 " + today.getNightType());
		} else {
			Weather today = weatherData.getWeathers().get(1);
			tvTempLowHigh.setText("最低 " + today.getLowTEMP() + "°");
			tvType.setText(today.getNightType());
		}
		// 获取图标
		int iconId = IconManager.getTypeIcon(tvType.getText().toString(), dayOrNight == 1);
		ivWeatherIcon.setImageResource(iconId);
	}

	/**
	 * 设置顶部可见
	 */
	public void setTopVisiable(boolean visiable) {
		if (visiable) {
			topView.animate().translationY(0).setDuration(400).start();
		} else {
			topView.animate().translationY(-topView.getHeight())
					.setDuration(400).start();
			topView.setTranslationY(10000);
		}
	}

	public void setRotateViewState(int state) {
		if (state == RotateView.STATE_DOWN) {
			rotateView.toDown();
		} else if (state == RotateView.STATE_HIDE) {
			rotateView.toHide();
		} else if (state == RotateView.STATE_UP) {
			rotateView.toUp();
		}
	}

	/**
	 * 设置即使天气可见
	 */
	public void setCenterVisiable(boolean visiable) {
		ObjectAnimator animator = null;
		PropertyValuesHolder valuesHolderY = null;
		PropertyValuesHolder valuesHolderAlpha = null;
		if (visiable) {
			valuesHolderY = PropertyValuesHolder.ofFloat("translationY",
					centerView.getHeight(), 0);
			valuesHolderAlpha = PropertyValuesHolder.ofFloat("alpha", 0, 1);
		} else {
			valuesHolderY = PropertyValuesHolder.ofFloat("translationY", 0,
					centerView.getHeight());
			valuesHolderAlpha = PropertyValuesHolder.ofFloat("alpha", 1, 0);
		}
		animator = ObjectAnimator.ofPropertyValuesHolder(centerView,
				valuesHolderY, valuesHolderAlpha);
		if (!visiable) {
			// 隐藏时动画结束后将其移除屏幕外，防止触摸事件
			animator.addListener(new AnimatorListenerAdapter() {
				@Override
				public void onAnimationEnd(Animator animation) {
					centerView.setTranslationY(10000);
				}
			});
		}
		animator.setDuration(400);
		animator.start();
	}
	
}
